package com.kt.controller;

import com.alibaba.fastjson.JSON;
import com.kt.domain.Product;
import com.kt.service.imp.CategoryServiceImp;
import com.kt.service.imp.ProductServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/findProduct.do")
public class FindProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String keyWord = req.getParameter("keyWord");
        ProductServiceImp productServiceImp = new ProductServiceImp();
        CategoryServiceImp categoryServiceImp = new CategoryServiceImp();
        List<Product> list = null;
        String[] brands = {"美的", "海尔", "格力", "奥克斯", "TCL", "小米", "海信", "华凌","申花", "荣事达", "康佳", "三菱电机", "松下", "科龙", "大金", "夏新", "统帅", "长虹"};
        // 防止中文乱码
        resp.setCharacterEncoding("utf-8");
        for (int i = 0; i < brands.length; i++) {
            if (keyWord.contains(brands[i])) {
                list = productServiceImp.findProductByBrand(brands[i]);
                resp.getWriter().write(JSON.toJSONString(list));
                return;
            }
        }
        String[] categories = {"挂壁式", "立柜式", "圆柱式"};
        for (String category: categories
             ) {
            if (keyWord.contains(category)) {
                list = productServiceImp.findProductByCid(categoryServiceImp.findByName(category).getCid());
                resp.getWriter().write(JSON.toJSONString(list));
                return;
            }
        }
        list = productServiceImp.findProductByKewWord(keyWord);
        resp.getWriter().write(JSON.toJSONString(list));
    }
}
